/*
 * @Author: HeAo
 * @Date: 2021-11-04 09:59:27
 * @LastEditTime: 2021-11-04 11:47:47
 * @LastEditors: HeAo
 * @Description:
 * @FilePath: \web2103-2105\web2103code\4-1-Nodejs\day05\briup-sc\routes\student.js
 * 别乱动！
 */
const express = require('express');
const Response = require('../utils/Response')
const router = express.Router();
// 导入mysql连接池
const pool = require('../utils/Connection')

const app = require('../app');

router.get('/findAll', (req, res) => {
  // 从连接池获取连接对象
  pool.getConnection((err, connection) => {
    if (err) throw err
    const sql = `select * from tab_student;`  // 定义sql语句
    // 使用连接对象查询
    connection.query(sql, (error, result) => {
      if (error) throw error
      // 将数据库查询结果响应给客户端
      res.send(new Response(20000, '查询成功', result))
      // 释放连接
      connection.release()
    })
  })
})

router.post('/saveOrUpdate', (req, res) => {
  let stu = req.body
  let sql = `insert into tab_student(name,gender) values('${stu.name}','${stu.gender}')`
  if (stu.id) {
    sql = `update tab_student set name = '${stu.name}', gender = '${stu.gender}' where id = ${stu.id}`
  }
  pool.getConnection((err, connection) => {
    if (err) throw err
    connection.query(sql, (error, result) => {
      if (error) throw error
      res.send(new Response(20000, '保存成功', null))
      connection.release()
    })
  })
})

router.delete('/deleteById', (req, res) => {
  const id = req.query.id
  const sql = `delete from tab_student where id = ${id}`
  pool.getConnection((err, connection) => {
    if (err) throw err
    connection.query(sql, (error, result) => {
      if (error) throw error
      res.send(new Response(20000, '删除成功', null))
      connection.release()
    })
  })
})


module.exports = router
